package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author by jojo
 * @Date 2022/3/2
 * @Description
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 查询所有自媒体文章
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1.参数校验
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        //校验分页参数
        dto.checkParam();
        //校验当前用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        //文章标题查
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道id查
        if (dto.getChannelId()!=null) {
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //文章状态
        if (dto.getStatus()!=null) {
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //时间区间查
        if (dto.getBeginPubDate()!=null) {
            wrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
        }
        if (dto.getEndPubDate()!=null){
            wrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }
        //用户id查
        if (wmUser.getId()!=null) {
            wrapper.eq(WmNews::getUserId,wmUser.getId());
        }
        //按照创建时间降序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> iPage = this.page(page, wrapper);
        //封装返回
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        result.setHost(webSite);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.校验参数 文章内容和标题不为空
        if (StringUtils.isBlank(dto.getContent())||StringUtils.isBlank(dto.getTitle())) {
           log.error("文章标题和内容不能为空");
           CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章标题和内容不能为空");
        }
        //判断是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //将dto 封装为 wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //将图片列表转为字符串
        String imagesToStr= imagesToString(dto.getImages());
        wmNews.setImages(imagesToStr);
        wmNews.setUserId(wmUser.getId());
        //type=-1 设置为 null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //2. 根据id 判断是保存还是修改
        saveOrUpdateByWmNews(wmNews);
        //判断状态 提交为1  草稿为0
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            //草稿
            return ResponseResult.okResult();
        }
        // 3. 保存文章内容 封面  和素材的关联关系
        // 3.1 抽取出内容中引用的素材url路径
        List<String> materialUrlList = parseContentByImages(dto.getContent());
        // 3.2保存内容和素材的关联关系
        if (CollectionUtils.isNotEmpty(materialUrlList)) {
            saveMaterialInfoForContent(materialUrlList,wmNews);
        }
        //3.3保存封面和素材的关联关系
        saveMaterialInfoForCover(materialUrlList,wmNews,dto);
        //3.4 发送待审核消息到mq
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送待审核消息到MQ队列。。。");
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.校验参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.执行查询
        WmNews wmNews = this.getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.封装返回
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult deleteNews(Integer id) {
        //校验参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查该用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //id查询文章表看有没有该文章
        WmNews wmNews = this.getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        //发布 status=9 并且是上架enable=1
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())&&WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"上架发布中不能删除");
        }
        //删除素材文章中间表
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getNewsId,id);
        wmNewsMaterialMapper.delete(wrapper);
        //再删除文章
        this.removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //检验参数
        Short enable = dto.getEnable();
        if (dto.getId()==null ||enable==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检验上下架状态码是否异常
        if (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"上下架状态码异常");
        }
        //id查询文章表看有没有该文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        //判断该文章是否是发布状态
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该文章不是发布状态，不能上下架");
        }
        //修改文章状态，同步到app端（后期做）TODO
        LambdaUpdateWrapper<WmNews> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(WmNews::getId,dto.getId());
        wrapper.set(WmNews::getEnable,enable);
        this.update(wrapper);
        //上下架发送消息通知  用于同步article 及 elasticsearch TODO
        if (wmNews.getArticleId()!=null){
            if (WemediaConstants.WM_NEWS_UP.equals(enable)) {
                //上架文章
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                        wmNews.getArticleId());
                log.info("上架文章发布MQ成功,Article ID: {}",wmNews.getArticleId());
            }else {
                //下架文章
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                        wmNews.getArticleId());
                log.info("下架文章发布MQ成功,Article ID: {}",wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findListByNews(NewsAuthDTO dto) {
        //检验参数
        dto.checkParam();
        //记录当前页
        Integer page = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        //判断前端传过来的标题为不为null
        if (StringUtils.isNotBlank(dto.getTitle())) {
            //拼接模糊查询所需要的%
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //分页查询
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        //统计有多少数据
        long listCount = wmNewsMapper.findListCount(dto);
        //封装返回数据
        PageResponseResult result = new PageResponseResult(page, dto.getSize(), listCount, listAndPage);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //参数校验
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        //查询文章信息
        WmNews wmNews = this.getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        //查询作者
        if (wmNews.getUserId()==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章没有作者。。。");
        }
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章关联的作者信息不存在");
        }
        //封装，返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        wmNewsVO.setAuthorName(wmUser.getName());
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        return ResponseResult.okResult(wmNewsVO);
    }
    /**
     *  自媒体文章人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(NewsAuthDTO dto, Short status) {
        //校验参数
        if (dto==null||dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"前端传来的参数和文章id不能为空");
        }
        //查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        //文章状态不能为9
        short newsStatus = wmNews.getStatus().shortValue();
        if (newsStatus== WmNews.Status.PUBLISHED.getCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该文章已经发布，无法再审核");
        }
        wmNews.setStatus(status);
        this.updateById(wmNews);
        // 发布延时任务，用于发布文章
        //发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        //当前时间
        long nowTime = System.currentTimeMillis();
        //相差时间
        long remainTime = publishTime - nowTime;
        //发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                message -> {
                    message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                    return message;
                }
        );
        log.info("手动动审核发布文章通知MQ成功，文章id：{}",wmNews.getId());
        //封装返回
        return ResponseResult.okResult();
    }

    /**
     * 保存封面和素材的关联关系
     * @param materialUrlList
     * @param wmNews
     * @param dto
     */
    private void saveMaterialInfoForCover(List<String> materialUrlList, WmNews wmNews, WmNewsDTO dto) {
        //原来的封面集合
        List<String> images = dto.getImages();
        //判断type是否是-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //-1需要自动生成封面
            int size = materialUrlList.size();
            //内容图片的个数小于等于2  则为单图截图一张图
            if (size>0 && size<=2) {
               images= materialUrlList.stream().limit(1).collect(Collectors.toList());
               wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }
            else if (size>2){
                images = materialUrlList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                //设置为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            // 如果有封面图 将图片集合转为字符串设置到wmNews.images 属性中
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imagesToString(images));
            }
            //修改wmNews
            updateById(wmNews);
        }
        // 如果不为空 保存关联关系
        if (CollectionUtils.isNotEmpty(images)) {
            images=images.stream().map(url->url.replaceAll(webSite,"").replace(" ",""))
                    .collect(Collectors.toList());
            saveRelationInfo(images,wmNews,WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     *  保存  文章内容涉及的图片 和 素材的关联关系
     *   0 内容引用
     *   1 主图引用
     * @param materialUrlList
     * @param wmNews
     */
    private void saveMaterialInfoForContent(List<String> materialUrlList, WmNews wmNews) {
        saveRelationInfo(materialUrlList,wmNews,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelationInfo(List<String> materialUrlList, WmNews wmNews, Short type) {
        // 1. 根据url路径列表 查询对应的id列表
        //数据库使用foreach遍历
        List<Integer> ids= wmMaterialMapper.selectRelationsIds(materialUrlList,WmThreadLocalUtils.getUser().getId());
        //3. 判断素材是否缺失
        if (CollectionUtils.isEmpty(ids)||ids.size()<materialUrlList.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章引用的素材缺失");
        }
        // 3. 根据素材id集合 文章id  引用类型 保存关联关系
        wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(),type);
    }

    private List<String> parseContentByImages(String content) {
        List<Map> contentMaps = JSON.parseArray(content, Map.class);
        return contentMaps.stream()
                //过滤type=image的数据
                .filter(m->WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                //提取每个map中value的值，都是图片路径
                .map(map -> (String)map.get("value"))
                //替换去除前缀
                .map(url->url.replaceAll(webSite,""))
                //去重
                .distinct()
                //收集到集合
                .collect(Collectors.toList());
    }

    /**
     * 保存或者修改文章
     * @param wmNews
     */
    private void saveOrUpdateByWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //设置为上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //判断 id为null就保存，有id就修改
        if (wmNews.getId()==null) {
            //保存
            this.save(wmNews);
        }else {
            //先删除 文章素材中间表的数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //修改
            this.updateById(wmNews);
        }

    }

    private String imagesToString(List<String> images) {
        if (CollectionUtils.isNotEmpty(images)) {
            return images.stream()
                    //去除前缀路径
                    .map(url->url.replaceAll(webSite,""))
                    .collect(Collectors.joining(","));
        }
        return null;
    }

}
